<?php
namespace app\common\model\approval;
use app\api\controller\Pub;
use app\common\model\user\User;
use app\common\model\power\Rolepower;
use app\common\model\company\Contract;
use app\common\model\orderhawa\HawaList;
use think\Model;

//审批角色列表
class Approvallog extends Model
{
    protected $table = 'approval_log';
    protected $pk    = 'Id';
    
    const STATEINT  = 1; //初始化 进行中
    const STATEING  = 1; //审批中
    const STATEOK   = 2; //审批完成
    const STATEERROR  = 3; //审批失败

    public function createuserinfo(){
        return $this->hasOne('app\common\model\User\User','UserId','CreateUserId');
    }

     /**
     * 状态分类
     * @param string $value [description]
     * @return [type]        [description]
     */
    public static function getStatusText($value = '')
    {
        $status = [-1=>'全部订单', 1 => '审批中', 2 => '审批完成'];
        if ($value !== '') {
            return $status[$value];
        }
        return $status;
    }


   /**
     * 分类
     * @param string $value [description]
     * @return [type]        [description]
     */
    public static function getTypeText($value = '')
    {
        $typelist = ['contract'=>'合同审批','assay' => '样品报价审批'];
        if ($value !== '') {
            return $typelist[$value];
        }
        return $typelist;
    }


    /**
     * 创建审批信息表
     * 如果关联化验单，关联
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function user_create($idata)
    {   
        if(empty($idata['CorrelationId'])){
            return moerr('缺少关联订单信息');
        }
        if(empty($idata['Type'])){
            return moerr('缺少分类信息');
        }
        //审批创建 限制，此处限制在获取规则时判断
        // if($idata['Type']!=='contract' && $idata['Type']!=='assay'){
        //     return moerr('暂不支持其他订单审批');
        // }
        $sb = ApprovalLog::where('Type',$idata['Type'])->where('CorrelationId',$idata['Id'])->where('IsDelete',0)->find();
        if(!empty($sb)){
            return moerr('无法创建新的审批表，因为有关联的审批订单信息，如需要从新申请，请先删除关联的审批信息。是否查看关联的审批信息？','approval/approval?aid='.$sb['Id'],true);
        }

        $rebate               = new Approvallog();
        $rebate->State        = Approvallog::STATEINT;
        $rebate->CreateTime   = date('Y-m-d H:i:s', time());
        $rebate->CreateUserId    = Pub::userid(); 
        $role   = Approvalrole::getrole($idata);
        $rebate->RulesPlan    = json_encode($role['data'],JSON_UNESCAPED_UNICODE);
        $rebate->ApprovalRoleId    = $role['Id'];
        $filed                = ['CorrelationId', 'Type'];
        foreach ($filed as $key => $value) {
            if (isset($idata[$value])) {
                $rebate->$value = $idata[$value];
            }
        }
        //保存
        $rebate->save();
        $id = $rebate->Id;
        return $id;
    }
    /**
     * 根据type 和 id 获取此模型的数据
     * @param [type] $type [description]
     * @param [type] $id   [description]
     */
    public static function type_id_getinfoModel($type,$id,$jump=false){
        $data = Approvallog::where('Type',$type)->where('CorrelationId',$id)->where('IsDelete',0)->with('createuserinfo');
        //判断权限 显示的数据
        $data = $data->visible(['createuserinfo'=>['Name','Iphone']]);
        if(!Rolepower::ispower('204016')){
           $data = $data->hidden(['OperationLog']); 
        }
        $data = $data->find();
        if(empty($data)){
            if($jump){
                return moerr('没有找到相关数据');
            }else{
                return [];
            }
        }else{
            $data = $data->toArray();
            //解析存储的信息
            $data['RulesPlan'] = json_decode($data['RulesPlan'],true);
            $userids = [];
            //取用户的userid
            foreach ($data['RulesPlan']['Rules'] as $key => $value) {
                $userids = array_merge($userids,$value['UserIds']);
            }
            $userinfo = User::where('UserId','in',$userids)->visible(['Name','UserId','Iphone'])->select()->toArray();
            $userinfo = arr_id_formate($userinfo,'UserId',true);
            //判断是否显示操作日志
            $showlog = Rolepower::ispower('204016');
            //给每个用户的名字赋值上
            foreach ($data['RulesPlan']['Rules'] as $key => $value) {
                foreach ($value['list'] as $uk => $uv) {
                    $data['RulesPlan']['Rules'][$key]['list'][$uk]['userinfo'] = $userinfo[$uv['UserId']];
                    if(!$showlog&&!empty($data['RulesPlan']['Rules'][$key]['list'][$uk]['OperationLog'])){
                        unset($data['RulesPlan']['Rules'][$key]['list'][$uk]['OperationLog']);
                    }
                }
            }
            return $data;
        }
    }
    /**
     * 修改审批信息
     * @param  [type] $newdata   [description]
     * @param  [type] $step      [description]
     * @param  [type] $listindex [description]
     * @param  [type] $data      [description]
     * @return [type]            [description]
     */
    public static function re_rules_list_info($newdata,$step,$listindex,$olddata){
        $lsdata = [];
        $mk = -1;
        foreach ($olddata['RulesPlan']['Rules'] as $key => $value) {
            if($value['Step']==$step){
                if(empty($value['list'][$listindex])){
                    return moerr('没有找到需要审批环节信息');
                }
                $lsdata = $value['list'][$listindex];
                if(empty($lsdata)){
                    return moerr('没有找到需要审批环节信息');
                }else{
                    $lsolddata = $olddata['RulesPlan']['Rules'][$key]['list'][$listindex];
                    if(empty($lsolddata)){
                        return moerr('没有找到需要审批环节信息');
                    }
                    $reinfo   = empty($lsolddata['OperationLog']) ? '' : $lsolddata['OperationLog'] . "\n";
                    $reinfo   = $reinfo . date('Y-m-d H:i', time()) . '进行了信息调整：';
                    $reflag   = 0;
                    //审批状态
                    if((int)$lsolddata['State']!==(int)$newdata['State']){
                        $reinfo = $reinfo.'将审批状态【'.((int)$lsolddata['State']==2?'通过':'驳回').'】调整为【'.((int)$newdata['State']==2?'通过':'驳回'). "】\n";
                        $lsolddata['State'] = (int)$newdata['State'];
                        $reflag = 1;
                    }
                    //审批意见
                    if($lsolddata['Note']!==$newdata['Note']){
                        $reinfo = $reinfo.'将审批意见【'.$lsolddata['Note'].'】调整为【'.$newdata['Note']."】\n";
                        $lsolddata['Note'] = $newdata['Note'];
                        $reflag = 1;
                    }
                    //审批图片
                    if($lsolddata['Img']!==$newdata['Img']){
                        $reinfo = $reinfo.'将审批图片【'.$lsolddata['Img'].'】调整为【'.$newdata['Img']."】\n";
                        $lsolddata['Img'] = $newdata['Img'];
                        $reflag = 1;
                    }
                    //修改的内容
                    if((int)$olddata['RulesPlan']['Rules'][$key]['list'][$listindex]['State']!==1){
                        $lsolddata['OperationLog'] = $reinfo;
                    }
                    //保存修改的内容
                    $mk = $key;
                }
            }
        }
        //如果没有修改信息
        if($reflag ==0){
            return sok();
        }
        if($mk==-1){
            return moerr('没有找到需要审批环节信息');
        }
        $lsolddata['Time'] = date('Y-m-d H:i:s',time());
        $olddata['RulesPlan']['Rules'][$mk]['list'][$listindex] = $lsolddata;
        $olddata['RulesPlan'] = json_encode($olddata['RulesPlan'],JSON_UNESCAPED_UNICODE);
        $appdata = Approvallog::get($olddata['Id']);
        $appdata->RulesPlan =  $olddata['RulesPlan'];
        $appdata->save();
        return sok();
    }

 
    
     //获取列表
      /**
     * 获取订单列表
     * @param  [type] $data    [主数据]
     * @param  string $type    [查询类型/hawa/buss]
     * @param  [type] $is_page [是否分页显示]
     * @return [type]          [description]
     */
    public static function usergetlist($data, $is_page = true)
    {

        $rdata    = new Approvallog;
        $userid = Pub::userid();

        //判断是否有选择筛选的类别 我申请的1  需要我审批的2  我审批的3
        $wherestr = '(';
        $typeids = $data['typeids'];
        if(!empty($typeids)){
            $typeids = explode(',',$typeids);
            //筛选 选择 显示我申请的
            if(in_array('1',$typeids)){
                $lsstr = '(CreateUserId = '.$userid.')';
               
                $wherestr = $wherestr . $lsstr;
            }

            //筛选 选择 显示需要我审批的 
            if(in_array('2',$typeids)){
                //显示我审批的时候 将分页关掉
                $is_page = false;
                $ApprovalRoleId = Approvalrole::user_get_manager_id();
                $lsstr = '(ApprovalRoleId in('.$ApprovalRoleId .') and (State = 1))';
                if($wherestr!=='('){
                    $wherestr = $wherestr .'or';
                }
                $wherestr = $wherestr . $lsstr;
            }

            //显示 我审批的3
            if(in_array('3',$typeids)){
                $ApprovalRoleId = Approvalrole::user_get_manager_id();
                $lsstr = '(ApprovalRoleId in('.$ApprovalRoleId .'))';
                if($wherestr!=='('){
                    $wherestr = $wherestr .'or';
                }
                $wherestr = $wherestr . $lsstr;
            }
        }
        if($wherestr!=='('){
            $rdata = $rdata->where($wherestr.')');
        }
     
        //删除标记的数据
        // if(empty($data['deletestate'])){
        //     $rdata = $rdata->where('IsDelete',0);
        // }else if($data['deletestate']==1){
        //     $rdata = $rdata->where('IsDelete',1);
        // }
        
        $rdata = $rdata->with(['createuserinfo'])->visible(['createuserinfo'=>['Name']])->hidden(['OperationLog']);

        $data['order'] = 'CreateTime desc';
        $option = come_model_option($data, $rdata, $is_page);

        $rdata = $option['rdata'];
        $data  = $option['data'];
        $rdata = $rdata->select();

        $lslist = $rdata->toArray();
        //筛选 选择 显示需要我审批的 
        if(!empty($typeids)&&in_array('2',$typeids)){
            foreach ($lslist as $key => $value) {
                $sh_sb =false;//审核哨兵变量 还未审核
                $lsv = json_decode($value['RulesPlan'],true);    
                foreach ($lsv['Rules'] as $vk => $vv) {
                    if((int)$vv['Step']==-1){
                        continue;//跳过直审的
                    }
                    foreach ($vv['list'] as $vvk => $vvv) {
                        if($vvv['UserId']==$userid){
                            if((int)$vvv['State']==2){
                                $sh_sb = true;//已经审核通过
                            }else{
                                $sh_sb = false;//未审核通过
                            }
                        }
                    }
                }
                if($sh_sb==true){
                    //删除已审核通过的
                    unset($lslist[$key]);
                }
            }
            $ndata['pageinfo'] = ['pageindex' => 1, 'pagemax' => 1]; 
        }
        $ndata['list'] = $lslist;
        $ndata['statetext'] = Approvallog::getStatusText();
     
        if ($is_page) {
            $ndata['pageinfo'] = ['pageindex' => $data['pageindex'], 'pagemax' => $data['count']];
        }
        return $ndata;
    }
}
